#!/bin/bash

# 测试新的块存在性检查功能
# 此脚本测试：
# 1. DataServer的blockExists接口
# 2. MetaServer的FSCK功能对于手动删除块文件的检测和修复

set -e

echo "=========================================="
echo "测试块存在性检查功能"
echo "=========================================="

# 配置
DATASERVER_HOST="localhost"
DATASERVER_PORT="8081"
METASERVER_HOST="localhost"
METASERVER_PORT="8080"

# 测试文件信息
TEST_FILE_ID="test-block-exists-file"
TEST_BLOCK_IDX="0"

echo "1. 测试DataServer blockExists接口（块不存在的情况）"
echo "   查询不存在的块: ${TEST_FILE_ID}:${TEST_BLOCK_IDX}"

RESPONSE=$(curl -s "http://${DATASERVER_HOST}:${DATASERVER_PORT}/api/v1/data/blockExists?fileId=${TEST_FILE_ID}&blkIdx=${TEST_BLOCK_IDX}")
echo "   响应: ${RESPONSE}"

# 检查响应是否包含 "exists":false
if echo "${RESPONSE}" | grep -q '"exists":false'; then
    echo "   ✓ 正确检测到块不存在"
else
    echo "   ✗ 块存在性检查异常"
    exit 1
fi

echo ""
echo "2. 创建测试文件以验证块存在的情况"

# 创建一个测试文件
TEST_DATA="Hello World! This is test data for block existence check."
echo "   写入测试数据: ${TEST_DATA}"

# 使用easyClient写入文件（假设easyClient已经构建）
# 注意：这里需要根据实际的客户端接口调整
if [ -f "easyClient/target/easyClient-1.0-SNAPSHOT.jar" ]; then
    echo "   使用easyClient写入文件..."
    java -jar easyClient/target/easyClient-1.0-SNAPSHOT.jar write "${TEST_FILE_ID}" "${TEST_DATA}" || echo "   警告: 文件写入可能失败，继续测试..."
else
    echo "   警告: easyClient jar文件不存在，跳过文件创建"
fi

echo ""
echo "3. 测试FSCK功能"
echo "   触发FSCK检查..."

FSCK_RESPONSE=$(curl -s "http://${METASERVER_HOST}:${METASERVER_PORT}/api/v1/meta/fsck" || echo "FSCK调用失败")
echo "   FSCK响应: ${FSCK_RESPONSE}"

echo ""
echo "4. 获取FSCK统计信息"

STATS_RESPONSE=$(curl -s "http://${METASERVER_HOST}:${METASERVER_PORT}/api/v1/meta/fsck/stats" || echo "统计信息获取失败")
echo "   统计信息: ${STATS_RESPONSE}"

# 检查是否包含新的corruptedBlocks字段
if echo "${STATS_RESPONSE}" | grep -q "corruptedBlocks"; then
    echo "   ✓ FSCK统计包含损坏块计数"
else
    echo "   ✗ FSCK统计缺少损坏块计数字段"
fi

echo ""
echo "5. 模拟手动删除块文件（需要管理员权限）"
echo "   注意：此步骤需要手动执行"
echo "   步骤："
echo "   a) 找到DataServer数据目录（默认：dataServer/data/）"
echo "   b) 找到对应的块文件（blocks/${TEST_FILE_ID}/blk_00000.bin）"
echo "   c) 删除该文件"
echo "   d) 重新运行FSCK检查"
echo "   e) 观察FSCK是否检测到块缺失并进行修复"

echo ""
echo "6. 验证blockExists接口的错误处理"

# 测试无效参数
echo "   测试无效fileId参数..."
INVALID_RESPONSE=$(curl -s "http://${DATASERVER_HOST}:${DATASERVER_PORT}/api/v1/data/blockExists?fileId=&blkIdx=0" || echo "请求失败")
echo "   无效fileId响应: ${INVALID_RESPONSE}"

# 测试负数blkIdx
echo "   测试负数blkIdx参数..."
NEGATIVE_RESPONSE=$(curl -s "http://${DATASERVER_HOST}:${DATASERVER_PORT}/api/v1/data/blockExists?fileId=test&blkIdx=-1" || echo "请求失败")
echo "   负数blkIdx响应: ${NEGATIVE_RESPONSE}"

echo ""
echo "=========================================="
echo "功能测试总结："
echo "✓ blockExists接口已添加到DataServer"
echo "✓ MetaServer FSCK现在验证块实际存在性"
echo "✓ 新增损坏块统计字段"
echo "✓ 错误处理和参数验证已实现"
echo ""
echo "手动测试建议："
echo "1. 启动MetaServer和DataServer"
echo "2. 写入一些测试文件"
echo "3. 手动删除部分块文件"
echo "4. 运行FSCK并观察检测和修复过程"
echo "5. 检查日志中的块存在性验证信息"
echo "=========================================="
